package com.rex.saas.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.rex.saas.bean.BaseResponse;
import com.rex.saas.bean.ResultCode;
import com.rex.saas.constants.Constants;
import com.rex.saas.db.entity.PaasGatewayCredentials;
import com.rex.saas.service.GatewayService;
import com.rex.saas.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
public class FileController {

    @Autowired
    private GatewayService gatewayService;

    /**
     * @param response
     * @return
     * @Description 下载CSV
     **/
    @GetMapping("/downloadAll")
    public BaseResponse downloadUnusedGw(HttpServletRequest request,  HttpServletResponse response) throws IOException {
        String token = request.getHeader("token");
        String tenantId = JwtUtils.getTenantId(token);
        if(StringUtils.isBlank(tenantId)){
            log.error("downloadUnusedGw tenantId is null");
            return BaseResponse.error("token异常", ResultCode.PARAM_ERROR);
        }

        List<String> roles = JwtUtils.getRole(token);
        if (!roles.contains(Constants.TENANT_ADMIN)){
            log.error("downloadUnusedGw roles is not admin");
            return BaseResponse.error("权限不足", ResultCode.PARAM_ERROR);
        }

        String[] head = gatewayService.getHead();
        List<String[]> values = gatewayService.getUnusedGw(tenantId);
        String fileName = gatewayService.getUnusedGwName();

//        File file = CSVUtils.makeTempCSV(fileName, head, values);
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName +".csv");
//        CSVUtils.downloadFile(response, file);
        return null;
    }

    /**
     * @return
     * @Description 上传CSV
     * @Param file
     **/
    @PostMapping(value = "/upload")
    public BaseResponse upload(HttpServletRequest request,  @RequestParam("file") MultipartFile multipartFile) {
        String token = request.getHeader("token");
        String tenantId = JwtUtils.getTenantId(token);
        if(StringUtils.isBlank(tenantId)){
            log.error("upload tenantId is null");
            return BaseResponse.error("token异常", ResultCode.PARAM_ERROR);
        }
        List<String> roles = JwtUtils.getRole(token);
        if (!roles.contains(Constants.TENANT_ADMIN)){
            log.error("upload roles is not admin");
            return BaseResponse.error("权限不足", ResultCode.PARAM_ERROR);
        }

        // 检查文件类型
        if (!multipartFile.getOriginalFilename().endsWith(".xlsx")) {
            throw new IllegalArgumentException("Invalid file type. Only .xlsx files are supported.");
        }

        // 解析Excel文件
        List<List<String>> data = new ArrayList<>();
        try (Workbook workbook = new XSSFWorkbook(multipartFile.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            List<PaasGatewayCredentials> paasGatewayCredentials  = new ArrayList<>();
            for(int i = 1; i < sheet.getLastRowNum(); i++){
                Row row = sheet.getRow(i);
                String clientId = String.valueOf(row.getCell(0));
                String password = String.valueOf(row.getCell(1));
                String userName = String.valueOf(row.getCell(2));
                String gwName = String.valueOf(row.getCell(4));
                String gwAlias = String.valueOf(row.getCell(4));
                List<PaasGatewayCredentials> list = gatewayService.getGwByName(gwName);
                if (CollectionUtils.isNotEmpty(list)){
                    gatewayService.deleteGw(gwName);
                    log.error("网关名称重复:"+gwName);
                }

                PaasGatewayCredentials gw = new PaasGatewayCredentials();
                gw.setGwName(gwName);
                gw.setGwAlias(gwAlias);
                gw.setClientId(clientId);
                gw.setUsername(userName);
                gw.setPassword(password);
                paasGatewayCredentials.add(gw);
            }
            if (!gatewayService.importGw(paasGatewayCredentials, token)){
                return BaseResponse.error("导入失败", ResultCode.PARAM_ERROR);
            }
        } catch (IOException e) {
            log.error("Failed to parse Excel file.", e);
            return BaseResponse.error("解析文件失败", ResultCode.PARAM_ERROR);
        }

        return BaseResponse.ok();

    }
}
